package cn.lls.controller.sa;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.base.util.MD5Util;
import cn.lls.base.util.TokenUtil;
import cn.lls.entity.admin.SuperadminEntity;
import cn.lls.service.IPermissionService;
import cn.lls.service.ISuperadminService;
import cn.lls.vo.common.LoginVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * 超级管理员登录控制器
 *
 * @ClassName SALoginController
 * @Author 划水艺术家
 * @Date 2022/11/19 18:50
 * @Version 1.0
 **/
@RestController
@RequestMapping("/sa/login")
@Api(tags = "超级管理员-登录控制器")
@Slf4j
public class SALoginController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private ISuperadminService superadminService;

    @PostMapping
    @ApiOperation(value = "超级管理员登录", notes = "超级管理员登录", response = R.class, httpMethod = "POST")
    public R saLogin(@RequestBody @Validated SuperadminEntity superadminEntity,
                     BindingResult bindingResult){
        LambdaQueryWrapper<SuperadminEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SuperadminEntity::getAccount, superadminEntity.getAccount());
        SuperadminEntity one = superadminService.getOne(queryWrapper);
        if (one == null){
            throw new LlsException(ResultCode.ACCOUNT_NOT_EXISTS);
        }
        if (!MD5Util.MD5Encode(superadminEntity.getLoginPassword()).equals(one.getLoginPassword()))
            return R.fail(ResultCode.PWD_FALSE, "密码错误");
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(TokenUtil.createToken(Long.parseLong(one.getAdminId().toString()),
                LlsEnum.LlsIdentify.SUPER_ADMIN));
        loginVO.setIdentify(LlsEnum.LlsIdentify.SUPER_ADMIN);
        loginVO.setUserId(Long.parseLong(one.getAdminId().toString()));
        loginVO.setMenuList(permissionService.getSuperAdminMenu());
        loginVO.setName("系统管理员");
        loginVO.setOrganName("六六顺团队");
//        log.info("loginVO = {}", loginVO);
        return R.success(loginVO);
    }
}
